<script lang="ts" setup>
import { useForm } from '@/hooks/web/useForm'
import { FormSchema } from '@/types/form'
import { LiveType, LiveTypeOptions } from '@/api/course/live'
import * as CourseLiveApi from '@/api/course/live'

const message = useMessage()
const { t } = useI18n()

const dialogVisible = ref(false)
const dialogTitle = ref('新增直播')
const formLoading = ref(false)
const formType = ref<'create' | 'update'>('create')

const schema = reactive<FormSchema[]>([
  {
    field: 'liveName',
    label: '直播名称',
    value: '',
    component: 'Input',
    formItemProps: {
      rules: [{ required: true, message: '请输入直播名称' }]
    }
  },
  {
    field: 'liveDesc',
    label: '直播描述',
    value: '',
    component: 'Input',
    componentProps: { type: 'textarea' },
    formItemProps: {
      rules: [
        // 长度不大于100个字符
        {
          max: 100,
          message: '目录描述不可超过100个字',
          trigger: ['blur', 'change']
        }
      ]
    }
  },
  {
    field: 'liveType',
    label: '直播类型',
    value: LiveType.ENTERPRISE,
    component: 'RadioButton',
    componentProps: {
      options: LiveTypeOptions
    }
  },
  {
    field: 'roomId',
    label: '直播间ID',
    value: '',
    component: 'Input',
    formItemProps: {
      rules: [{ required: true, message: '请输入直播间ID' }]
    }
  }
])

const { register, elFormRef, methods: formMethods } = useForm()

const open = (type: 'create' | 'update', id?: string) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'update' ? '编辑直播' : '新增直播'
  formType.value = type

  if (type === 'update') {
    formLoading.value = true
    CourseLiveApi.get(id!).then((data) => {
      console.log('update: ', data)
      formMethods.setValues(data)
      formLoading.value = false
    })
  }
}
defineExpose({ open })

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!elFormRef.value) return
  const valid = await elFormRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true

  try {
    const formData = (await formMethods.getFormData()) || {}

    if (formType.value === 'create') {
      // 转换表单
      const data = { ...formData }
      console.log('创建直播：', data)
      await CourseLiveApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      // 转换表单
      const data = { ...formData, id: formData.id }
      console.log('更新直播：', data)
      await CourseLiveApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>

<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="500">
    <Form :schema="schema" @register="register" />
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
